/*
 * Copyright 2022 learn-netty4 Project
 *
 * The learn-netty4 Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package com.jxw.cloudpen.web.microsoft.stremspeed;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static io.netty.handler.codec.http.HttpMethod.GET;
import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;

/**
 * 同时处理消息和
 */
@Slf4j
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
    private static final String WEBSOCKET_PATH = "/websocket";
    private WebSocketServerHandshaker handshaker;
    //线程数量=内核*2
    private static int N_CPUS = Runtime.getRuntime().availableProcessors()*2;
    private static ExecutorService pool = Executors.newFixedThreadPool(N_CPUS);
    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws IOException {
        //根据消息类型，处理两种不同的消息
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        } else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws IOException {
        // 处理异常
        if (!req.decoderResult().isSuccess()) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), BAD_REQUEST,
                    ctx.alloc().buffer(0)));
            return;
        }

        // 只允许get请求
        if (!GET.equals(req.method())) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(req.protocolVersion(), FORBIDDEN,
                    ctx.alloc().buffer(0)));
            return;
        }

        // websocket握手
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                getWebSocketLocation(req), null, true, 50 * 1024 * 1024);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {
        // 处理各种websocket的frame信息
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }
        if (frame instanceof PingWebSocketFrame) {
            ctx.write(new PongWebSocketFrame(frame.content().retain()));
            return;
        }
        if (frame instanceof TextWebSocketFrame) {
            ByteBuf content = frame.content();
            byte[] byteArray = new byte[content.readableBytes()];
            content.readBytes(byteArray);
            StreamData streamData = JSONObject.parseObject(new String(byteArray), StreamData.class);

            if (1 == streamData.getType()) {
                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                streamData.setClientId(uuid);
                try {
                    MyStreamSpeedTest.open(streamData.getLanguageCode());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ByteBuf responseBuffer = ctx.alloc().buffer();
                StremSpeedMsg stremSpeedMsg = new StremSpeedMsg();
                stremSpeedMsg.setClientId(streamData.getClientId());
                stremSpeedMsg.setType(streamData.getType());
                stremSpeedMsg.setLanguageCode(streamData.getLanguageCode());
                responseBuffer.writeBytes(JSONObject.toJSONString(stremSpeedMsg).getBytes(StandardCharsets.UTF_8));
                ctx.channel().writeAndFlush(new TextWebSocketFrame(responseBuffer));
            } else if (2 == streamData.getType()) {
                executeBusin(streamData,ctx);
            } else if (3 == streamData.getType()) {
                try {
                    MyStreamSpeedTest.stop();
                } catch (Exception e) {
                    e.printStackTrace();
                }
//                sendEndMsg(ctx, streamData);
            }else if (4 == streamData.getType()) {
//                sendEndMsg(ctx, streamData);
            }
            return;
        }
        if (frame instanceof BinaryWebSocketFrame) {
            //解析
//            ByteBuf content = frame.content();
//            byte[] byteArray = new byte[content.readableBytes()];
//            content.readBytes(byteArray);
        }
    }

    private void executeBusin(StreamData streamData, ChannelHandlerContext ctx) {
        //执行识别
        try {
            MyStreamSpeedTest.langPushStrem(streamData.getData());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


    private void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {
        // 生成错误页面
        HttpResponseStatus responseStatus = res.status();
        if (responseStatus.code() != 200) {
            ByteBufUtil.writeUtf8(res.content(), responseStatus.toString());
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }
        // 发送response
        boolean keepAlive = HttpUtil.isKeepAlive(req) && responseStatus.code() == 200;
        HttpUtil.setKeepAlive(res, keepAlive);
        ChannelFuture future = ctx.write(res);
        if (!keepAlive) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        // 连接断开时执行的代码
        System.out.println("Connection closed.");
        MyStreamSpeedTest.close();
        super.channelInactive(ctx); // 调用父类的实现以确保适当的资源释放（如果有的话）
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 异常处理
        log.error("出现异常", cause);
        ctx.close();
    }

    private static String getWebSocketLocation(FullHttpRequest req) {
        String location = req.headers().get(HttpHeaderNames.HOST) + WEBSOCKET_PATH;
        return "ws://" + location;
    }
}
